package cn.wolfcode.util;

import cn.wolfcode.qo.JsonResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 对控制器进行增强
 * 利用aop
 */
@ControllerAdvice
public class ControllerExceptionHandler {

    /**
     * 当前的方法用于捕获指定的异常(RuntimeException)
     *
     * handlerMethod 出现异常的那个处理方法
     */
    @ExceptionHandler(RuntimeException.class)
    public Object handler(RuntimeException e, HttpServletResponse response, HandlerMethod handlerMethod) throws IOException {
        //方便开发的时候找bug
        e.printStackTrace();
        //判断如果是ajax对应的方法，就返回JsonResult,判断是否有ResponseBody注解
        if(handlerMethod.hasMethodAnnotation(ResponseBody.class)){
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(new JsonResult(false,"操作失败")));
            return null;
        }else{
            //如果不是，就返回错误的视图页面
            //model.addAttribute("")
            return "common/error";
        }
    }

    /**
     * 捕获没有权限的异常
     * @param e
     * @param response
     * @param handlerMethod
     * @return
     * @throws IOException
     */
    @ExceptionHandler(UnauthorizedException.class)
    public Object handlerUnauthorized(RuntimeException e, HttpServletResponse response, HandlerMethod handlerMethod) throws IOException {
        //方便开发的时候找bug
        e.printStackTrace();
        //判断如果是ajax对应的方法，就返回JsonResult,判断是否有ResponseBody注解
        if(handlerMethod.hasMethodAnnotation(ResponseBody.class)){
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(new JsonResult(false,"您没有权限操作！")));
            return null;
        }else{
            //如果不是，就返回错误的视图页面
            //model.addAttribute("")
            return "common/nopermission";
        }
    }





}
